#!/usr/bin/env python

import os
import json
import webapp2
import logging
import pprint
import cgi
import datetime

from collections import defaultdict
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
from google.appengine.ext.webapp.util import login_required

from models.models import *

class LandingHandler(webapp2.RequestHandler):
    def get(self):

        user = users.get_current_user()
      
        # We are using the template module to output the page.
        path = os.path.join(os.path.dirname(__file__), '../templates' ,'landing.html')
        self.response.out.write(template.render( path, {}))



class MainHandler(webapp2.RequestHandler):
    # @login_required
    def get(self):
        user = users.get_current_user()
        captions = Caption.query().order(Caption.date).fetch()
        art_pieces = ArtPiece.query().fetch()

        art_dict = {}
        art_list = []
        i = 0

        for art in art_pieces:
            art_dict[art.key.id()] = i
            o = {
                'image':{
                    'key':art.key.urlsafe(),
                    'image_url':art.image_url
                },
                'captions':[]
            }
            art_list.append(o)
            i += 1

        for cap in captions:
            parent_key = cap.key.parent()
            art_piece = parent_key.get()

            o = {
                'key': cap.key.urlsafe(),
                'caption_text':cap.caption_text,
                'date':cap.date,
                'id':cap.key.id(),
                # 'fav':fav
            }
            art_index = art_dict[parent_key.id()]
            art_list[art_index]['captions'].append(o)
        

        site_url = self.request.url
        print site_url


        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps({"art_list":art_list, "site_url":site_url}))

    
class AddCaptionHandler(webapp2.RequestHandler):
   
    def post(self):
        user = users.get_current_user()
        key_img = self.request.get("key")
        print 'MainHandler key_img %s' % key_img
        print self.request.get("owncaption")
        
        if key_img:
            key = ndb.Key(urlsafe=key_img)#hidden
            print key
            caption = Caption(user=user, caption_text=self.request.get("owncaption"), parent=key)#entered in caption
            caption.put()#saving
            r = { "key": caption.key.urlsafe() }#passing key back
        else:
            r = {'error': 'Invalid Caption.'}

            if 'error' in r:
                self.response.status_int = 500

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(r))


class AddFavHandler(webapp2.RequestHandler):
    
    def post(self):

        user = users.get_current_user()
        user_id = user.user_id()
        print "user id is"
        print user_id 

        print "user"
        key = ndb.Key(urlsafe=self.request.get("key"))
        print key
        if key:
            addedCaptions = CaptionFavs.query(CaptionFavs.user==user, ancestor=key).get()#when getting a new one CaptionFavs
            print addedCaptions
            r = 'success'
            # caption = addedCaptions.get()
            if addedCaptions is None:
                print "HI"
                print addedCaptions
                #check to see if the cap_key is in the FavCap model
                if not addedCaptions:
                    cap_fav = CaptionFavs(user=user, parent=key)
                    cap_fav.put()
                    r = 'added favourite'
                else:
                    r = {'error': 'add failed.'}

            else:
                addedCaptions.key.delete()
                r = 'deleted favourite'
        else:
            r = {'error': 'Invalid parameters.'}

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(r))       



class AboutHandler(webapp2.RequestHandler):
    def get(self):

        user = users.get_current_user()
      
        # We are using the template module to output the page.
        path = os.path.join(os.path.dirname(__file__), '../templates' ,'about.html')
        self.response.out.write(template.render( path, {}))



class RecapHandler(webapp2.RequestHandler):
    @login_required
    def get(self):
        user = users.get_current_user()
        caption_favs = CaptionFavs.query(CaptionFavs.user==user).fetch()
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps({"caption_favs": caption_favs}))






